﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PServiceBus.Core.Interface;
using System.Net;
using PServiceBus.Transports;
using System.Diagnostics;
using PServiceBus.Core.Runtime.Transports;
using System.Net.NetworkInformation;

namespace PServiceBus.MessageProxy {
    public static class TcpHelper {
        private static int _portCounter = 0;
        
        private static string IPAddress {
            get {
                return Dns.GetHostAddresses(Dns.GetHostName()).First(
                    ip => ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).ToString();
            }
        }

        public static int GetAvailablePort() {
            var port = Process.GetCurrentProcess().Id + (++_portCounter);
            var properties = IPGlobalProperties.GetIPGlobalProperties();
            var tcpEndPoints = properties.GetActiveTcpListeners();

            if (tcpEndPoints.Any(x => x.Port == port)) {
                _portCounter++;
                return GetAvailablePort();
            }
            return port;
        }

        public static ITransport Transport {
            get {
                return PServiceBus.Services.Gateway.Runtime.Transport.New<TcpTransport>(transport =>
                {
                    transport.Format = TransportFormat.Xml;
                    transport.IPAddress = IPAddress;
                    transport.Port = GetAvailablePort();
                });
            }
        }
    }
}
